/**
 *
 */
package jp.seraph.jsmf.motion;

import jp.seraph.jsade.core.Player;
import jp.seraph.jsade.core.World;
import jp.seraph.jsade.task.AbstractTask;
import jp.seraph.jsade.task.AgentTask;
import jp.seraph.jsade.util.Executor;
import jp.seraph.jsmf.message.MessageUtil;
import jp.seraph.jspf.pose.DefaultPose;
import jp.seraph.jspf.pose.DefaultPoseSet;
import jp.seraph.jspf.pose.Pose;

/**
 *
 *
 */
public class ElementTask extends AbstractTask {
    /**
     *
     */
    public ElementTask(MotionElement aElement, SessionTask aSessionTask) {
        mTargetTask = new DefaultPoseSet(aElement.getPoseElement()).toTask();
        mSessionTask = aSessionTask;
        mBaseElement = aElement;
        mCurrentPercent = 0;
        mBasePose = null;
        mFinished = false;

        mTargetTask.addCompletedListener(new Executor(){
            public void execute(){
                mFinished = true;
                complete();
            }
        });
    }

    private AgentTask mTargetTask;
    private SessionTask mSessionTask;
    private MotionElement mBaseElement;
    private int mCurrentPercent;
    private Pose mBasePose;
    private boolean mFinished;

    /**
     *
     * @see jp.seraph.jsade.task.AbstractTask#execute(jp.seraph.jsade.core.World, jp.seraph.jsade.core.Player)
     */
    @Override
    public void execute(World aWorld, Player aPlayer) {
        if(mBasePose == null)
            mBasePose = new DefaultPose(aWorld.getModelManager());

        mCurrentPercent = mBaseElement.getCurrentPercentage(mBasePose, new DefaultPose(aWorld.getModelManager()));
        mTargetTask.execute(aWorld, aPlayer);
    }

    /**
     *
     * @see jp.seraph.jsade.task.AbstractTask#canExecute()
     */
    @Override
    public boolean canExecute() {
        String tConditionElementName = mBaseElement.getConditionElementName();
        if("".equals(tConditionElementName))
            return true;

        ElementTask tConditionTask = mSessionTask.getElementTask(tConditionElementName);
        if(tConditionTask == null)
            throw new RuntimeException(MessageUtil.noConditionElement(tConditionElementName));

        return tConditionTask.getPercent() >= mBaseElement.getStartPercentage();
    }

    public int getPercent(){
        if(mFinished)
            return 100;

        return mCurrentPercent;
    }
}
